import 'package:shared_preferences/shared_preferences.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import '../common/spider.dart';

class Article {
  late final String title;
  late final String author;
  late final String content;

  Article({required this.title, required this.author, required this.content});

  get titleAndAuthor => title + '_' + author;
}

class ArticleModel {
  double _lineSpacingTimes = 1.5;
  double _contentFontSize = 16;
  Article _currentArticle =
      Article(title: "title", author: "author", content: "content");

  List<String> _favoriteArticlesList = [];

  List<String> get favoriteArticlesList => _favoriteArticlesList;

  late final Set<String> _favoriteArticlesSet;
  late final Database _database;

  ArticleModel() {
    getDataBase();
  }

  getDataBase() async {
    _database = await openDatabase(
      join(await getDatabasesPath(), "article_database.dab"),
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE Articles(title_author TEXT PRIMARY KEY, content TEXT)',
        );
      },
      version: 1,
    );

    final List<Map<String, dynamic>> maps = await _database.query('Articles');

    var articleList = List.generate(maps.length, (i) {
      return maps[i]['title_author'].toString();
    });

    _favoriteArticlesSet = Set.from(articleList);
    _favoriteArticlesList = articleList;
  }

  bool isCurArticleFavorite() {
    return _favoriteArticlesSet.contains(_currentArticle.titleAndAuthor);
  }

  setCurArticleFavorite() {
    _favoriteArticlesSet.add(_currentArticle.titleAndAuthor);
    favoriteArticlesList.add(_currentArticle.titleAndAuthor);
    _database.insert(
      "Articles",
      {
        "title_author": _currentArticle.titleAndAuthor,
        "content": _currentArticle.content
      },
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  setCurArticleUnFavorite() {
    setArticleUnFavorite(_currentArticle.titleAndAuthor);
  }

  setArticleUnFavorite(String title_author) {
    _favoriteArticlesSet.remove(title_author);
    favoriteArticlesList.remove(title_author);
    _database.delete(
      "Articles",
      where: 'title_author=?',
      whereArgs: [title_author],
    );
  }

  get currentArticle => _currentArticle;

  Future<void> getPrefs() async {
    var prefs = await SharedPreferences.getInstance();
    _contentFontSize = prefs.getDouble("ContentFontSize") ?? _contentFontSize;
    _lineSpacingTimes =
        prefs.getDouble("LineSpacingTimes") ?? _lineSpacingTimes;
  }

  double getContentFontSize() => _contentFontSize;

  updateContentFontSize(value) {
    _contentFontSize = value;
    SharedPreferences.getInstance()
        .then((prefs) => prefs.setDouble("ContentFontSize", _contentFontSize));
  }

  double getLineSpacingTimes() => _lineSpacingTimes;

  updateLineSpacingTimes(value) {
    _lineSpacingTimes = value;
    SharedPreferences.getInstance().then(
        (prefs) => prefs.setDouble("LineSpacingTimes", _lineSpacingTimes));
  }

  Future<Article> getNewArticle() async {
    Article? newArticle = await ArticleCatcher.getArticle();
    if (newArticle == null) {
      throw "文章获取错误";
    }
    _currentArticle = newArticle;
    return newArticle;
  }

  Future<Article> getFavoriteArticle(String title_author) async {
    var result = await _database.query(
      "Articles",
      where: 'title_author=?',
      whereArgs: [title_author],
    );

    var tmp = result[0]["title_author"].toString().split("_");

    Article newArticle = Article(title: tmp[0], author: tmp[1], content: result[0]["content"].toString());
    _currentArticle = newArticle;
    return newArticle;
  }
}
